package com.sinosoft.web.common.shiro.interceptors;


import cn.com.sinux.spring.commons.SystemConfig;
import com.sinosoft.hydra.um.domain.model.DirectoryType;
import com.sinosoft.hydra.um.domain.permission.TDirectory;
import com.sinosoft.hydra.um.helper.AuthContextHelper;
import com.sinosoft.hydra.um.services.DirectoryService;
import com.sinosoft.hydra.um.utils.AppUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * URL API拦截处理
 *
 * @author oujianlin@sinux.com.cn
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private DirectoryService directoryService;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        TDirectory directory = directoryService.findByKey(DirectoryType.valueOf("DIRECTORY_BAKING"), null);
        String wait = request.getContextPath() + "/app/api/home/redirectWait";
        if (!wait.equals(request.getRequestURI()) && directory != null && !"none".equals(directory.getDirValue())) {
            wait += "?d=" + directory.getDirValue();
            response.sendRedirect(wait);
        }
        AuthContextHelper.setLoginUser(AppUtils.createLoginUser(request, response));
        return true;
    }

    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        request.setAttribute("url", request.getRequestURI());
        request.setAttribute("params", request.getQueryString());
        if (modelAndView != null) {
            modelAndView.addObject("SystemConfig", SystemConfig.getProperties());
            modelAndView.addObject("loginUser", AuthContextHelper.getLoginUser());
            if (StringUtils.isNotBlank(request.getParameter("uuid"))) {
                modelAndView.addObject("uuid", request.getParameter("uuid"));
            }
        }
    }
}
